package com.share.tools;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.share.constants.OssConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author caifan
 * @created 2021/8/19
 * description: 阿里云OSS上传
 */
public class OSSUtil {

    public static String upload(OSS ossClient, MultipartFile file, String fileDir, String bucket) throws IOException {
        // 指定文件目录
        if (StringUtils.isEmpty(fileDir)) {
            fileDir = OssConstant.OSS_VENDOR_DIR;
        }
        String fileName = file.getOriginalFilename();
        String filePath = fileDir + OssConstant.FILE_SEPERATOR + fileName;
        return upload(ossClient, file.getInputStream(), filePath, bucket);
    }

    public static String upload(OSS ossClient, InputStream inputStream, String fileDir, String bucket) throws IOException {
        ossClient.putObject(bucket, fileDir, inputStream);
        return OssConstant.OSS_PREFIX + bucket + OssConstant.DOT + OssConstant.OSS_ENDPOINT_PREFIX + OssConstant.FILE_SEPERATOR + fileDir;
    }

    public static InputStream download(OSS oss, String bucket, String fileName) {
        OSSObject ossObject = oss.getObject(bucket, fileName);
        return ossObject.getObjectContent();
    }

}
